// chrome 扩展官方文档  http://www.kkh86.com/it/chrome-extension-doc/extensions/tabs.html#method-get
class IconUI {
  constructor() {
    this.host = ''; // 保存当前tab页的域名，据此判断当前页面有没有开启过FreeCopy扩展
    this.disableIcon = 'disable.png';
    this.enableIcon = 'enable.png';
    this.disableTitle = 'FreeCopy已关闭';
    this.enableTitle = 'FreeCopy已开启';
  }

  setTitle(title) {
    chrome.browserAction.setTitle({
      title: title,
    });
  }

  setIcon(path) {
    chrome.browserAction.setIcon({
      path: path,
    });
  }

  sendMessage(tabId, isEnabled) {
    // 使用 chrome.tabs API 与浏览器的标签页系统交互
    // 扩展程序向内容脚本发消息
    chrome.tabs.sendMessage(tabId, {
      isEnabled: isEnabled,
    });
  }
  setEnable(tabId) {
    this.setIcon(this.enableIcon);
    this.setTitle(this.enableTitle);
    this.sendMessage(tabId, true);
  }

  setDisable(tabId) {
    this.setIcon(this.disableIcon);
    this.setTitle(this.disableTitle);
    this.sendMessage(tabId, false);
  }
  parseHost(url) {
    var domain = url.split('/');
    return domain[2] || '';
  }
  setRecord(val) {
    localStorage.setItem(`${this.host}`, val);
  }
  getRecord() {
    return localStorage.getItem(`${this.host}`);
  }
  setSiteFreeCopy(tab) {
    const { id, url } = tab;
    this.host = this.parseHost(url);
    console.log(`\n\n 开启/关闭自由复制扩展功能: status=${this.getRecord()} host=${this.host} \n\n`);
    // 如果没有开启，则开启，反之则禁用
    if (this.getRecord() != 'true') {
      this.setRecord(true);
      this.setEnable(id);
    } else {
      this.setRecord(false);
      this.setDisable(id);
    }
  }
  restoreSiteFreeCopy() {
    // 查询当前选中tab的属性
    chrome.tabs.getSelected(null, (tab) => {
      console.log('当前选中的tab页属性:', tab);
      const { id, url,status} = tab;
      // 防止onUpdated事件触发三次, complete状态兼容onUpdated和onActived事件
      if (status != 'complete') {
        return;
      }

      // 从url中解析出当前页面域名
      this.host = this.parseHost(url);
      console.log('\n\n 恢复页面的自由复制扩展设置：status=${this.getRecord()} host=${this.host} \n\n');

      // 从localStorage中查询当前页面是否开启过free-copy功能,并复原设置状态
      if (this.getRecord() == 'true') {
        this.setEnable(id);
      } else {
        this.setDisable(id);
      }
    });
  }
}

const UI = new IconUI();

// 浏览器按钮(可以包含图标、工具提示、徽章和弹出内容）单击事件
chrome.browserAction.onClicked.addListener((currentTab) => {
  console.log('bg onClicked-点击扩展图标:', currentTab);
  UI.setSiteFreeCopy(currentTab);
});

// 切换页面时触发--页面从开启了FreeCopy扩展的网站切换到未开启FreeCopy的网站,需要将Freecopy插件设置为禁用状态
chrome.tabs.onActivated.addListener((newTab) => {
  console.log('bg onActivated-标签页切换：', newTab);
  UI.restoreSiteFreeCopy();
});

// 当前标签页内容改变时触发
chrome.tabs.onUpdated.addListener((currentTabId, changeInfo) => {
  console.log('bg onUpdated-标签页内容改变：', currentTabId, changeInfo);
  UI.restoreSiteFreeCopy();
});

// 接收内容脚本发送过来的消息
// chrome.runtime.onMessage.addListener((response, sender) => {
//   console.log('bg response sender', response, sender);
// });
